import React, { Component } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';

export default class RouterView extends Component {

  render() {

    let { routes } = this.props;
    let componentList = routes.filter((v) => v.path);
    let redirectList = routes.filter((v) => v.to)
    return (
      <Switch>
        {componentList.map((v, i) => {
          return <Route key={i} path={v.path} render={(props) => {
            if (v.auth && !window.sessionStorage.getItem('token')) {
              return (
                <Redirect key={v.to} to={{
                  pathname: '/page/login',
                  query: {
                    path: v.path
                  }
                }}>
                </Redirect>
              )
            } else {
              return (<v.component
                routes={v.children || []} {...props}></v.component>)
            }
          }}></Route>
        })}

        {redirectList.map((v) => {
          return <Redirect key={v.from} from={v.from} to={v.to} ></Redirect>
        })}
      </Switch>
    )
  }
}
